import 'package:flutter/material.dart';
import 'package:audio_waveforms/audio_waveforms.dart';
import 'package:flutter_cache_manager/file.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:oramemo/common/styles/text_styles.dart';
import 'package:oramemo/common/utils/time_util.dart';
import 'package:oramemo/common/langs/text_key.dart';

import 'audio_player_controller.dart';

class AudioPlayerWidget extends StatefulWidget {
  final String? audioUrl;
  final AudioPlayerController? controller;

  const AudioPlayerWidget({
    super.key,
    required this.audioUrl,
    this.controller,
  });

  @override
  State<AudioPlayerWidget> createState() => _AudioPlayerWidgetState();
}

class _AudioPlayerWidgetState extends State<AudioPlayerWidget> {
  late PlayerController _playerController;
  bool _isPlaying = false;
  bool _isLoad = false;
  Duration _duration = Duration.zero;
  Duration _position = Duration.zero;
  double _speed = 1.0;
  double _volume = 1.0;
  bool _isSpeed = false;
  bool _isVolume = false;
  File? _file;

  final playerWaveStyle = PlayerWaveStyle(
    fixedWaveColor: Colors.blue.withOpacity(0.3),
    liveWaveColor: Colors.blue,
    seekLineColor: const Color(0xFFDD484F),
    seekLineThickness: 1,
    waveThickness: 2,
    scaleFactor: 300,
    spacing: 3,
  );

  @override
  void initState() {
    super.initState();
    _initializePlayer();
  }

  Future<void> _initializePlayer() async {
    if (widget.audioUrl?.isNotEmpty != true) {
      return;
    }
    try {
      _playerController = PlayerController();
      widget.controller?.setPlayerController(_playerController);
      _file = await DefaultCacheManager().getSingleFile(widget.audioUrl!);
      if (_file?.path.isNotEmpty != true) {
        return;
      }
      await _playerController.preparePlayer(
        path: _file!.path,
        shouldExtractWaveform: true,
      );

      // 获取音频时长
      final durationInMillis = await _playerController.getDuration();
      _duration = Duration(milliseconds: durationInMillis );

      // 监听播放进度
      _playerController.onCurrentDurationChanged.listen((duration) {
        if (mounted) {
          setState(() {
            _position = Duration(milliseconds: duration);
            widget.controller?.position = _position;
          });
        }
      });

      // 监听播放状态
      _playerController.onPlayerStateChanged.listen((state) {
        if (mounted) {
          setState(() {
            _isPlaying = state == PlayerState.playing;
            // 当播放完成时重置播放器
            if (state == PlayerState.stopped) {
              _resetPlayer();
            }
          });
        }
      });

      setState(() {
        _isLoad = true;
      });
    } catch (e) {
      print('Error initializing player: $e');
    }
  }

  // 添加重置播放器方法
  Future<void> _resetPlayer() async {
    try {
      await _playerController.seekTo(0);
      setState(() {
        _position = Duration.zero;
        _isPlaying = false;
      });
    } catch (e) {
      print('Error resetting player: $e');
    }
  }

  @override
  void dispose() {
    _playerController.dispose();
    super.dispose();
  }

  // 播放/暂停
  Future<void> _togglePlay() async {
    try {
      if (_isPlaying) {
        await _playerController.pausePlayer();
      } else {
        // 如果已经播放完成（在结尾），先重置到开始位置
        if (_position >= _duration) {
          await _resetPlayer();
        }
        await _playerController.startPlayer();
        _playerController.setFinishMode(finishMode: FinishMode.pause);
      }
    } catch (e) {
      print('Error toggling play: $e');
    }
  }

  // 快进15秒
  Future<void> _fastForward() async {
    try {
      final newPosition = _position + const Duration(seconds: 10);
      if (newPosition <= _duration) {
        await _playerController.seekTo(newPosition.inMilliseconds);
      } else {
        await _playerController.seekTo(_duration.inMilliseconds);
      }
    } catch (e) {
      print('Error fast forwarding: $e');
    }
  }

  // 快退15秒
  Future<void> _rewind() async {
    try {
      final newPosition = _position - const Duration(seconds: 10);
      if (newPosition >= Duration.zero) {
        await _playerController.seekTo(newPosition.inMilliseconds);
      } else {
        await _playerController.seekTo(0);
      }
    } catch (e) {
      print('Error rewinding: $e');
    }
  }

  // 调整语速
  Future<void> _updateSpeed(double speed) async {
    try {
      await _playerController.setRate(speed);
      setState(() {
        _speed = speed;
      });
    } catch (e) {
      print('Error updating speed: $e');
    }
  }

  // 调整音量
  Future<void> _updateVolume(double volume) async {
    try {
      await _playerController.setVolume(volume);
      setState(() {
        _volume = volume;
      });
    } catch (e) {
      print('Error updating volume: $e');
    }
  }

  // 格式化时间
  String _formatDuration(Duration duration) {
    return TimeUtils.formatDuration(duration);
  }

  @override
  Widget build(BuildContext context) {
    if (!_isLoad) {
      return Center(
        child: Column(
          children: [
            SizedBox(height: 10),
            CircularProgressIndicator(),
            SizedBox(height: 5),
            Text(TextKey.audioPlayerLoading.tr)
          ],
        ),
      );
    }

    return Container(
      padding: EdgeInsets.only(top: 10, bottom: 10),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.only(
              bottomLeft: Radius.circular(20),
              bottomRight: Radius.circular(20))),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 波形显示区域
          Container(
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(8))),
            margin: EdgeInsets.fromLTRB(15, 0, 15, 0),
            child: AudioFileWaveforms(
              size: Size(MediaQuery.of(context).size.width, 112),
              playerController: _playerController,
              waveformType: WaveformType.long,
              playerWaveStyle: playerWaveStyle,
            ),
          ),

          // 时间显示
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                SizedBox(
                  width: 35,
                ),
                Text(_formatDuration(_position), style: TextStyles.textBold16),
                Text(_formatDuration(_duration)),
              ],
            ),
          ),

          // 控制按钮
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              IconButton(
                icon: const Icon(Icons.speed, size: 28),
                onPressed: () {
                  setState(() {
                    _isSpeed = !_isSpeed;
                    _isVolume = false;
                  });
                },
              ),
              IconButton(
                icon: const Icon(Icons.replay_10, size: 28),
                onPressed: _rewind,
                tooltip: TextKey.audioPlayerRewind.tr,
              ),
              IconButton(
                icon:
                    Icon(_isPlaying ? Icons.pause : Icons.play_arrow, size: 32),
                onPressed: _togglePlay,
                tooltip: _isPlaying ? TextKey.audioPlayerPause.tr : TextKey.audioPlayerPlay.tr,
              ),
              IconButton(
                icon: const Icon(Icons.forward_10, size: 28),
                onPressed: _fastForward,
                tooltip: TextKey.audioPlayerFastForward.tr,
              ),
              IconButton(
                icon: const Icon(Icons.volume_up, size: 28),
                onPressed: () {
                  setState(() {
                    _isSpeed = false;
                    _isVolume = !_isVolume;
                  });
                },
                tooltip: TextKey.audioPlayerVolume.tr,
              ),
            ],
          ),

          // 语速调节
          if (_isSpeed)
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: Row(
                children: [
                  Text('${TextKey.audioPlayerSpeed.tr}: ${_speed.toStringAsFixed(1)}x'),
                  Expanded(
                    child: Slider(
                      value: _speed,
                      min: 0.5,
                      max: 3.0,
                      divisions: 25,
                      label: '${_speed.toStringAsFixed(1)}x',
                      onChanged: _updateSpeed,
                    ),
                  ),
                ],
              ),
            ),

          // 音量调节
          if (_isVolume)
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: Row(
                children: [
                  Text('${TextKey.audioPlayerVolume.tr}: ${_volume.toStringAsFixed(1)}'),
                  Expanded(
                    child: Slider(
                      value: _volume,
                      min: 0.0,
                      max: 1.0,
                      onChanged: _updateVolume,
                    ),
                  ),
                ],
              ),
            ),
        ],
      ),
    );
  }
}
